<style>
@import "./register.css";
</style>

<template>
  <view>
    <u-toast ref="uToast"/>
    <view class="content">
      <u--form ref="uForm" :model="user" labelPosition="left"
               bindsubmit="formSubmit" bindreset="formReset">
        <!-- 用户名 -->
        <u-form-item class="u-form-item" label="用户名" prop="owner.ownerNickname" borderBottom>
          <u-input v-model="user.owner.ownerNickname"
                   placeholder="请输入用户名"
                   border="none"/>
        </u-form-item>
        <!--手机号-->
        <u-form-item class="u-form-item" label="手机号码" prop="owner.ownerPhoneNumber" border-bottom>
          <u-input v-model="user.owner.ownerPhoneNumber" border="none" placeholder="请输入手机号码"/>
        </u-form-item>
        <!-- 密码 -->
        <u-form-item class="u-form-item" label="密码" prop="owner.ownerPassword" borderBottom>
          <u-input v-model="user.owner.ownerPassword" placeholder="请输入密码"
                   type="ownerPassword" border="none"/>
        </u-form-item>
        <!--真实姓名-->
        <u-form-item class="u-form-item" label="真实姓名" prop="owner.ownerRealName" borderBottom>
          <u-input v-model="user.owner.ownerRealName" placeholder="请输入真实姓名" border="none"/>
        </u-form-item>
        <!--性别-->
        <u-form-item class="u-form-item" @click="showSex = true;"
                     label="性别"
                     prop="owner.ownerGender"
                     borderBottom>
          <u-input v-model="user.owner.ownerGender"
                   disabled
                   disabledColor=""
                   placeholder="请选择性别"
                   border="none"/>
          <u-icon slot="right" name="arrow-right"/>
        </u-form-item>
        <!--性别选择-->
        <u-action-sheet :show="showSex"
                        :actions="actions"
                        title="请选择性别"
                        description="如果选择保密会报错"
                        @close="showSex = false"
                        @select="sexSelect"/>
        <!--年龄-->
        <u-form-item class="u-form-item" label="年龄"
                     prop="owner.ownerAge"
                     borderBottom>
          <u-input v-model="user.owner.ownerAge" border="none"/>
        </u-form-item>
        <!--身份证号-->
        <u-form-item class="u-form-item" label="身份证号码"
                     prop="owner.ownerIdCard"
                     borderBottom
                     :rules="[
                      { required: true, message: '请输入身份证号码', trigger: ['blur', 'change'] },
                      { validator: validateIdCard, trigger: ['blur', 'change'] }
                     ]">
          <u-input v-model="user.owner.ownerIdCard" border="none" placeholder="请输入身份证号码"/>
        </u-form-item>
        <!--qq号-->
        <u-form-item class="u-form-item" label="QQ号码"
                     prop="owner.ownerQqNumber"
                     border-bottom>
          <u-input v-model="user.owner.ownerQqNumber" border="none" placeholder="请输入QQ号码"/>
        </u-form-item>
        <!--微信号-->
        <u-form-item class="u-form-item" label="微信号"
                     prop="owner.ownerWechatId"
                     border-bottom>
          <u-input v-model="user.owner.ownerWechatId" border="none" placeholder="请输入微信号"/>
        </u-form-item>
        <!-- 出生日期-->
        <view style="display: flex; height: 88rpx;">
          <text class="label">出生日期:</text>
          <picker mode="date" @change="handleDateChange">
            <view class="date-picker">
              <text v-if="!user.owner.ownerBirthday" class="placeholder">请选择出生日期</text>
              {{ user.owner.ownerBirthday }}
            </view>
          </picker>
        </view>

        <!-- 头像上传 -->
        <view class="container">
          选择头像
          <view @tap="chooseImage"
                style="background: #fff8f8; height: 160rpx; width: 160rpx; border-radius: 50%;">
            <!-- 显示已选择头像 -->
            <image v-if="selectedAvatar" class="selected-avatar" :src="selectedAvatar"/>
            <view v-else style="margin-top: 50rpx;">未选择头像
            </view>
          </view>
        </view>

        <button class="btn" @click="handleSubmit">注册</button>
      </u--form>

      <view class="xieyi">
        <text class="agree">注册则视为同意</text>
        <text class="opinion">《xx用户注册协议》</text>
      </view>
    </view>
  </view>
</template>

<script>
import {JudgeOwner} from "@/common/utils";

export default {
  data() {
    return {
      showSex: false,
      showBirthday: false,
      user: {
        owner: {
          ownerRealName: '',
          ownerGender: '',
          ownerAge: '', // 新增年龄字段
          ownerIdCard: '',
          ownerPhoneNumber: '',
          ownerQqNumber: '',
          ownerWechatId: '',
          ownerBirthday: '',
          ownerNickname: '',
          ownerPassword: '',
          ownerPortrait: '' //头像
        }
      },
      selectedAvatar: '', // 存储已选择头像的路径
      actions: [{
        name: '男',
      },
        {
          name: '女',
        },
        {
          name: '保密',
        },
      ],
      rules: {
        // 真实姓名
        'owner.ownerRealName': [
          {
            required: true,
            trigger: ['blur', 'change'],
            max: 10,
            message: '请填写真实姓名'
          },
          {
            pattern: /^\S*$/,
            message: '不能出现空格'
          },
        ],
        // 性别
        'owner.ownerGender': {
          max: 1,
          required: true,
          trigger: ['blur', 'change'],
          message: '请选择男或女'
        },
        // 年龄
        'owner.ownerAge': [
          {
            type: 'number',
            required: true,
            trigger: ['blur', 'change'],
            message: '请填写年龄'
          },
          {
            pattern: /^\S*$/,
            message: '不能出现空格'
          },
        ],
        // 身份证
        'owner.ownerIdCard': {
          required: true,
          trigger: ['blur', 'change'],
          validator: (rule, value, callback) => {
            const idCardRegex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
            if (!idCardRegex.test(value)) {
              callback(new Error('请输入有效的身份证号码'));
            } else {
              callback();
            }
          },
        },
        // 手机号
        'owner.ownerPhoneNumber': {
          type: 'number',
          required: true,
          len: 11,
          message: '请输入正确手机号码',
          trigger: ['blur', 'change']
        },
        // QQ号
        'owner.ownerQqNumber': [
          {
            type: 'number',
            required: false,
            min: 5,
            max: 12,
            message: 'QQ号码为5-12位数字',
          },
          {
            pattern: /^\S*$/,
            message: '不能出现空格'
          },
        ],
        // 微信号
        'owner.ownerWechatId': [
          {
            required: false,
            trigger: ['blur', 'change'],
            max: 20,
            message: '微信号不能超过20个字符',
          },
          {
            pattern: /^[a-zA-Z0-9_-]{1,21}$/,
            message: '微信号只有字母和数字以及-_',
          },
        ],
        //用户名
        'owner.ownerNickname': [
          {
            required: true,
            trigger: ['blur', 'change'],
            message: '请输入用户名'
          },
          {
            pattern: /^\S*$/,
            message: '不能出现空格'
          },
        ],
        //密码
        'owner.ownerPassword': [
          {
            required: true,
            trigger: ['blur', 'change'],
            min: 6,
            max: 18,
            message: '密码为6-18位'
          },
          {
            pattern: /^[a-zA-Z0-9_-]{1,20}$/,
            message: '密码只能使用字母、数字和-_',
          },
        ],
      },
      radio: '',
      switchVal: false,
    }
  },

  methods: {
    sexSelect(e) {
      this.user.owner.ownerGender = e.name
      this.$refs.uForm.validateField('owner.ownerGender')
    },
    // 日期
    handleDateChange(event) {
      // 处理日期选择器变化
      this.user.owner.ownerBirthday = event.mp.detail.value;
    },
    // 选择头像的点击事件
    chooseImage() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.selectedAvatar = tempFilePath;
          this.uploadToOSS(tempFilePath);
        },
        fail: (error) => {
          console.error('选择头像失败', error);
        },
      });
    },

    // 上传头像
    uploadToOSS(tempFilePath) {
      wx.uploadFile({
        url: 'http://localhost:8080/uni-app/upload',
        filePath: tempFilePath,
        name: 'file',
        header: {
          'token': uni.getStorageSync('token'),
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('上传成功', data);
          if (data.code === 200) {
            const imageUrl = data.data;
            // 将图片路径存起来
            this.user.owner.ownerPortrait = imageUrl;
            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 2000
            });
          } else {
            console.error('上传失败', data.message);
            wx.showToast({
              title: '上传失败: ' + data.message,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (error) => {
          console.error('上传失败', error);
        },
      });
    },

    // 表单验证 => 注册
    async handleSubmit() {
      const isValid = await this.$refs.uForm.validate();
      if (isValid) {
        this.registerUser();
      } else {
        console.log('注册失败');
      }
    },
    // 注册
    async registerUser() {
      this.$http.put('/uni-app/addRegister', this.user.owner)
          .then(res => {
            if (res.data.code === 200) {
              console.log(res.data.data)
              uni.showToast({
                title: '注册成功，正在自动登录',
                icon: 'success',
                duration: 1500,
                success: () => {
                  //登录
                  let owner = {ownerPhoneNumber: '', ownerPassword: ''};
                  owner.ownerPhoneNumber = this.user.owner.ownerPhoneNumber;
                  owner.ownerPassword = this.user.owner.ownerPassword;
                  console.log(owner)
                  this.$http.post('/uni-app/appLogin', owner).then(res => {
                    //保存数据
                    if (res.data.code === 200) {
                      uni.setStorageSync('token', res.data.data.token);
                      uni.setStorageSync('ownerId', res.data.data.ownerId);
                      uni.setStorageSync('tokenTime', new Date())
                      uni.setStorageSync('ownerName', res.data.data.ownerNickname);
                      uni.setStorageSync('ownerPhoneNumber', res.data.data.ownerPhoneNumber)
                      JudgeOwner();
                      uni.switchTab({url: '/pages/index/index'})
                    } else {
                      console.log(res.data.message)
                    }
                  });
                }
              });
            } else if (res.data.message === '手机号已被注册') {
              this.$refs.uToast.show({
                type: 'error',
                message: "手机号已被注册！",
                iconUrl: 'static/uToastIcon/error.png',
              });
            } else {
              console.error('注册失败', res.data.message);
            }
          })
          .catch(error => {
            console.error('注册请求失败', error);
          });
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  }
}
</script>
